package net.asrsmid.invoker;

import java.util.Map;

import javax.xml.ws.Holder;

import net.asrsmid.config.AsRsAuthMode;
import net.asrsmid.config.AsRsAuthenticator;
import net.asrsmid.connection.rs.RsWebserviceProxy;

import com.microsoft.rs2005.ArrayOfString;
import com.microsoft.rs2005.ArrayOfWarning;
import com.microsoft.rs2005.ExecutionHeader;
import com.microsoft.rs2005.ExecutionInfo;

/**
 * @author Chen WANG
 * @version 1.0
 * @created 05-mai-2011 11:53:12
 */
public class RsWebserviceInvoker {	
	private RsWebserviceProxy proxy;
	
	/**
	 * @param proxy
	 */
	public RsWebserviceInvoker(RsWebserviceProxy proxy) {
		this.proxy = proxy;
	}

	/**
	 * 
	 * @param reportPath
	 * @param reportParamsMap
	 * @param reportFormat
	 * @param deviceInfo
	 * @param auth
	 */
	public byte[] getReport(String reportPath, Map<String, String> reportParamsMap, String reportFormat, String deviceInfo, AsRsAuthenticator auth) {
		byte[] reportResult = null;
		try {
			// ---- get ws proxy
			if (proxy == null) return null;

			// ---- basic authentication if necessary
			if (auth != null && auth.getAuthMode() == AsRsAuthMode.BASIC) {
				proxy.setAuthentication(auth.getUsername(), auth.getPassword());
			}

			// ---- setting execution header and id
			ExecutionInfo execInfo = proxy.loadReport(reportPath, null);
			ExecutionHeader execHeader = new ExecutionHeader();
			execHeader.setExecutionID(execInfo.getExecutionID());
			proxy.setOutboundHeaders(execHeader);

			// ---- setting parameters if necessary
			proxy.setExecutionParameters(reportParamsMap);

			// ---- rendering report
			Holder<byte[]> result = new Holder<byte[]>();
			Holder<String> extension = new Holder<String>();
			Holder<String> mimeType = new Holder<String>();
			Holder<String> encoding = new Holder<String>();
			Holder<ArrayOfWarning> warnings = new Holder<ArrayOfWarning>();
			Holder<ArrayOfString> streamIDs = new Holder<ArrayOfString>();
			proxy.render(reportFormat, deviceInfo, result, extension, mimeType, encoding, warnings, streamIDs);

			// ---- returning result
			reportResult = result.value;
		} catch (Throwable t) {
			t.printStackTrace();
		} finally {
			try {
				if (proxy != null) proxy.release();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// return report byte stream
		return reportResult;
	}
}